package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import cn.com.kh.signUtil
import com.alibaba.fastjson.JSON
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import com.alibaba.fastjson.parser.Feature
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.bouncycastle.util.encoders.Base64Encoder
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource
import sun.misc.BASE64Decoder
import sun.misc.BASE64Encoder
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.lang.reflect.Array
import java.text.SimpleDateFormat

/**
 * 合同模板拼接
 */

public class apiFDDMoudle implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiFDDMoudle.class);
    private static String APPKEY = "QwM7K28TpIk6USVFq9NfHDcW";
    private static String URL = "http://qztest.dbc61.com/api";
    private String charset = "utf-8"; //设置字符集
    private int timeout = 100000; //设置请求超时时间
    private int enableSSLflag = 0;
    private String LOCALURL = "";

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 初始化返回参数
        JSONObject result = new JSONObject();
        String v_interfacetype = request.getParameter("interfacetype");

        JSONObject resultJson = null;
        //接收客户端调用参数
        String callJson = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;

        while ((line = iny.readLine()) != null) {
            callJson += line;
        }
        JSONArray conArr = new JSONArray();
        log.info("【调用请求信息】：" + callJson);

        try {
            LOCALURL = KHDBConfig.getAPIURL(eliteBean, "Groovy-Inner");
            URL = KHDBConfig.getAPIURL(eliteBean, "fddurl");

            HashMap<String, Object> headMap = new HashMap<>();
            headMap.put("Content-Type", "application/json");

            JSONObject inJson = JSONObject.fromObject(callJson);
            log.info("【inJson】：" + inJson);

            String tabname = inJson.getString("tabcname");//tabc表名
            //String ModelID = inJson.getString("ModelID");//模板id 根据物业号查询出来的
            String businessnumber = inJson.getString("businessnumber");//物业号
            String workorderid = inJson.getString("workroderid");//工单id
            String contractid = inJson.getString("contractid");//合同id
            String contractype = inJson.getString("contractype");//工单类型

            JSONArray customernumber = inJson.getJSONArray("customernumber");
            log.debug("【customernumber】：" + customernumber);
            log.debug("【customernumber.size】：" + customernumber.size());

            int nullfalg = 0;
            for (int i = 0; i < customernumber.size(); i++) {
                    if(customernumber.get(i).get(0) ==''){
                        nullfalg ++;
                    }
            }

            log.debug("【nullfalg】：" + nullfalg);
            if(nullfalg == customernumber.size()){
                result.put("code", 1010);
                result.put("msg", "法大大id为空,请联系管理员");
                JSONObject curJson = new JSONObject();
                curJson.put("deslcode", -2);
                curJson.put("dealinfo", "法大大id为空,请联系管理员");
                conArr.add(curJson);
                return result;
            }

/*
            String customernumberstr = inJson.getString("customernumber");
            log.debug("【customernumberstr】：" + customernumberstr);
            String[][] customernumber = JSON.parseObject(customernumberstr, String[][].class);
            log.debug("【customernumber】：" + customernumber);
 */

            //根据物业号查询模板编号
            List hjx_businessnumber = new ArrayList<>();
            log.info("【工单类型】：" + contractype);

            if (contractype == '退租') {
                hjx_businessnumber = eliteBean.chaxun_sql("SELECT fc.contractfile_name FROM fdd_bao_seatno fb LEFT JOIN ( WITH RECURSIVE recursion ( FDDGroup_id, FDDGroup_name, PARENTID ) AS ( SELECT F1.FDDGroup_id, F1.FDDGroup_name, F1.PARENTID FROM fdd_group_bao F1 WHERE F1.FDDGroup_id = 'JZI7Y6' UNION ALL SELECT F2.FDDGroup_id, F2.FDDGroup_name, F2.PARENTID FROM fdd_group_bao F2, recursion F3 WHERE F2.PARENTID = F3.FDDGroup_id ) SELECT F.FDDGroup_id, F.FDDGroup_name, F.PARENTID FROM recursion F WHERE F.FDDGroup_id != 'JZI7Y6' ) f ON fb.FDDGroup_id = f.FDDGroup_id LEFT JOIN fdd_bao_contract fc ON fb.FDDGroup_id = fc.FDDGroup_id WHERE f.FDDGroup_id IS NOT NULL AND fb.seatno = '" + businessnumber + "'", "dataSource");
            } else {
                hjx_businessnumber = eliteBean.chaxun_sql("SELECT fc.contractfile_name FROM fdd_bao_seatno fb LEFT JOIN ( WITH RECURSIVE recursion ( FDDGroup_id, FDDGroup_name, PARENTID ) AS ( SELECT F1.FDDGroup_id, F1.FDDGroup_name, F1.PARENTID FROM fdd_group_bao F1 WHERE F1.FDDGroup_id = 'JFKBZF' UNION ALL SELECT F2.FDDGroup_id, F2.FDDGroup_name, F2.PARENTID FROM fdd_group_bao F2, recursion F3 WHERE F2.PARENTID = F3.FDDGroup_id ) SELECT F.FDDGroup_id, F.FDDGroup_name, F.PARENTID FROM recursion F WHERE F.FDDGroup_id != 'JFKBZF' ) f ON fb.FDDGroup_id = f.FDDGroup_id LEFT JOIN fdd_bao_contract fc ON fb.FDDGroup_id = fc.FDDGroup_id WHERE f.FDDGroup_id IS NOT NULL AND fb.seatno = '" + businessnumber + "'", "dataSource");
            }

            log.info("【合同包内模板】：" + hjx_businessnumber);

            if (hjx_businessnumber.size() > 0) {//循环遍历
                int arrInt = hjx_businessnumber.size();
                for (int t = 0; t < arrInt; t++) {
                    String ModelID = hjx_businessnumber.get(t).get("contractfile_name");
                    log.info("【合同模板id】：" + ModelID);
                    String tt = t;
                    String sqls = "select fdd_key, work_key from fdd_contract_key where contractfileid='" + ModelID + "'";
                    List resultlist = eliteBean.chaxun_sql(sqls, "dataSource");
                    if (resultlist.size() == 0) {
                        JSONObject curJson = new JSONObject();
                        curJson.put("deslcode", -1);
                        curJson.put("dealinfo", "当前模板没有维护key：" + ModelID);
                        conArr.add(curJson);
                        log.debug("【当前模板没有维护key】：" + ModelID);
                        continue;
                        //return result
                    }

                    String objparam = "";
                    for (def i = 0; i < resultlist.size(); i++) {
                        String work_keyt = resultlist[i].get("work_key");

                        if (work_keyt == "workorderworkorderid_zl") {
                            work_keyt = "case when '" + contractid + "' !='' then '" + contractid + "' when workorderworkorderid_zl is not null and workorderworkorderid_zl !='' then workorderworkorderid_zl else '/' end";
                        } else {
                            work_keyt = (work_keyt == "zl_leaseapplicationtimestart" || work_keyt == "zl_leaseapplicationtimesend" || work_keyt == "stagesttime1" || work_keyt == "stagesttime2" || work_keyt == "stagesttime3" || work_keyt == "leaseapplicationtimestart" || work_keyt == "leaseapplicationtimesend" || work_keyt == "releasetime" || work_keyt == "contract_signtime") ? "if (ISNULL(" + work_keyt + ")=1 or LENGTH(TRIM(" + work_keyt + "))=0,'/'," + "DATE_FORMAT(" + work_keyt + ",'%Y年%m月%d日')" + ")" : "if (ISNULL(" + work_keyt + ")=1 or LENGTH(TRIM(" + work_keyt + "))=0,'/'," + work_keyt + ")";
                        }
                        log.debug("合同模版字段映射工单Tabc字段预处理： " + work_keyt + "  法大大Key： " + resultlist[i].get("fdd_key"));
                        objparam = objparam + "," + work_keyt + " as '" + resultlist[i].get("fdd_key") + "'";
                    }

                    objparam = objparam.startsWith(",") ? objparam.substring(1) : objparam;
                    log.debug("【objparam】：" + objparam);

                    if (objparam) {
                        String tabcsql = "select " + objparam + " from " + tabname + " ta left join objective o on o.objective_guid = ta.relation_id where o.workorderid = '" + workorderid + "'";
                        log.debug("【tabcsql】：" + tabcsql);
                        List tabcParams = eliteBean.chaxun_sql(tabcsql, "dataSource");
                        log.debug("【tabcParams】：" + tabcParams);

                        JSONObject tabcJson = new JSONObject();
                        Map<String, Object> tabcmap = tabcParams.get(0);
                        log.debug("-------------------------------------------------");

                        log.debug("【tabcmap】：" + tabcmap);
                        for (String key : tabcmap.keySet()) {
                            log.debug("【key】：" + key);
                            tabcJson.put(key, tabcmap.get(key).toString());
                        }

                        String contractid2 = contractid + tt
                        log.debug("【contractid】：" + contractid);

                        List signature_pzf = eliteBean.chaxun_sql("select signature from fdd_contract_file where contractfileid = '" + ModelID + "'", "dataSource");
                        String signature = signature_pzf.get(0).get("signature");

                        inJson.remove("tabcname");
                        inJson.remove("businessnumber");
                        inJson.remove("contractid");
                        inJson.put("ModelID", ModelID);
                        inJson.put("workorderid", workorderid);
                        inJson.put("contractid", contractid2);
                        inJson.put("signature", signature);
                        inJson.put("data", tabcJson);
                        def resultss = Util.doHttpPostUseHead(LOCALURL + "/api/apiCreateContract?interfacetype=create", inJson.toString().replace("\\n", ""), charset, timeout, enableSSLflag, headMap);
                        result = JSONObject.fromObject(resultss);

                        JSONObject curJson = new JSONObject();
                        curJson.put("deslcode", 1);
                        curJson.put("dealinfo", "调用处理成功");
                        conArr.add(curJson);
                        log.debug("--------------------------------------------" + result + "-----------------------------------------");

                        if (result.code == "1") {
                            int arrInt2 = customernumber.size();
                            //往 fdd_agreement_list 表中记录乙方数据
                            List signerGuidList = new ArrayList();
                            List signerNameList = new ArrayList();
                            log.debug("--------------------------------------------" + customernumber + "-----------------------------------------");
                            for (int n = 0; n < arrInt2; n++) {
                                String customerid2 = customernumber.get(n).get(0);
                                String customertype = customernumber.get(n).get(1);
                                String customertype2 = "";

                                log.debug("【customertype】：" + customertype);
                                if (customertype == "个人") {
                                    customertype2 = "1"
                                } else {
                                    customertype2 = "2"
                                }

                                if (customerid2 != '' && customerid2 != null) {
                                    String[] custTaskDealSQL = new String[1];
                                    custTaskDealSQL[0] = "INSERT INTO fdd_agreement_list(agreementduid, ModelID, businessnumber, workorderid, contractid, customerid,ht_state, ht_type, pushsigning, ordernum, customertype, createddate) VALUES (UUID(), '" + ModelID + "', '" + businessnumber + "', '" + workorderid + "', '" + contractid2 + "', '" + customerid2 + "', '未签署', '客户', '未推送','0', '" + customertype2 + "', now())"
                                    int[] batchSQLResult = eliteBean.updateBatch(custTaskDealSQL, "dataSource");
                                    log.debug("往fdd_agreement_list写入SQL返回结果：" + batchSQLResult.toString());

                                    List customerNameList = eliteBean.chaxun_sql("Select customername From customer Where FDD_CUSTOMERID = '" + customerid2 + "'", "dataSource");
                                    String customerName = customerNameList[0].get("customername");
                                    log.info("【接收方名称】：" + customerName);
                                    signerGuidList.add(customerid2);
                                    signerNameList.add(customerName);
                                }
                            }

                            //往 fdd_agreement_list 表中记录甲方数据
                            List senderGuidList = new ArrayList();
                            List senderNameList = new ArrayList();
                            //根据物业号查询包里面存在的签署方和签章方
                            List hjx_customeridlist = new ArrayList<>();
                            log.debug("【contractype】：" + contractype);
                            if (contractype == '退租') {
                                hjx_customeridlist = eliteBean.chaxun_sql("SELECT DISTINCT fa.customerid, fa.fdd_type, fa.ordernum, CONCAT(fa.yth_gsname,'-',fa.fdd_type) as sender_name FROM fdd_bao_seatno fb LEFT JOIN ( WITH RECURSIVE recursion ( FDDGroup_id, FDDGroup_name, PARENTID ) AS ( SELECT F1.FDDGroup_id, F1.FDDGroup_name, F1.PARENTID FROM fdd_group_bao F1 WHERE F1.FDDGroup_id = 'JZI7Y6' UNION ALL SELECT F2.FDDGroup_id, F2.FDDGroup_name, F2.PARENTID FROM fdd_group_bao F2, recursion F3 WHERE F2.PARENTID = F3.FDDGroup_id ) SELECT F.FDDGroup_id, F.FDDGroup_name, F.PARENTID FROM recursion F WHERE F.FDDGroup_id != 'JZI7Y6' ) f ON fb.FDDGroup_id = f.FDDGroup_id LEFT JOIN fdd_bao_contract fc ON fb.FDDGroup_id = fc.FDDGroup_id LEFT JOIN fdd_contract_file ff ON fc.contractfile_guid = ff.contractfile_guid LEFT JOIN fdd_admin fa ON FIND_IN_SET( fa.CUSTOMERID, ff.FDD_CUSTOMERID ) WHERE f.FDDGroup_id IS NOT NULL AND fb.seatno = '" + businessnumber + "' AND fa.customerid != ''", "dataSource");
                            } else {
                                hjx_customeridlist = eliteBean.chaxun_sql("SELECT DISTINCT fa.customerid, fa.fdd_type, fa.ordernum, CONCAT(fa.yth_gsname,'-',fa.fdd_type) as sender_name FROM fdd_bao_seatno fb LEFT JOIN ( WITH RECURSIVE recursion ( FDDGroup_id, FDDGroup_name, PARENTID ) AS ( SELECT F1.FDDGroup_id, F1.FDDGroup_name, F1.PARENTID FROM fdd_group_bao F1 WHERE F1.FDDGroup_id = 'JFKBZF' UNION ALL SELECT F2.FDDGroup_id, F2.FDDGroup_name, F2.PARENTID FROM fdd_group_bao F2, recursion F3 WHERE F2.PARENTID = F3.FDDGroup_id ) SELECT F.FDDGroup_id, F.FDDGroup_name, F.PARENTID FROM recursion F WHERE F.FDDGroup_id != 'JFKBZF' ) f ON fb.FDDGroup_id = f.FDDGroup_id LEFT JOIN fdd_bao_contract fc ON fb.FDDGroup_id = fc.FDDGroup_id LEFT JOIN fdd_contract_file ff ON fc.contractfile_guid = ff.contractfile_guid LEFT JOIN fdd_admin fa ON FIND_IN_SET( fa.CUSTOMERID, ff.FDD_CUSTOMERID ) WHERE f.FDDGroup_id IS NOT NULL AND fb.seatno = '" + businessnumber + "' AND fa.customerid != ''", "dataSource");
                            }
                            log.debug("【hjx_customeridlist】：" + hjx_customeridlist);
                            if (hjx_customeridlist.size() > 0) {//循环遍历
                                int arrInt3 = hjx_customeridlist.size();
                                log.debug("【arrInt3】：" + arrInt3);
                                for (int f = 0; f < arrInt3; f++) {
                                    String fdd_customerid = hjx_customeridlist.get(f).get("customerid");
                                    String fdd_type = hjx_customeridlist.get(f).get("fdd_type");
                                    String fdd_ordernum = hjx_customeridlist.get(f).get("ordernum");
                                    log.debug("【fdd_customerid】：" + fdd_customerid + " \\ " + fdd_type);

                                    String[] custTaskDealSQL2 = new String[1];
                                    custTaskDealSQL2[0] = "INSERT INTO fdd_agreement_list( agreementduid, ModelID, businessnumber, workorderid, contractid, customerid,ht_state, ht_type, pushsigning, ordernum, createddate) VALUES (UUID(), '" + ModelID + "', '" + businessnumber + "', '" + workorderid + "', '" + contractid2 + "','" + fdd_customerid + "','未签署','" + fdd_type + "','未推送','" + fdd_ordernum + "',now())"
                                    int[] batchSQLResult2 = eliteBean.updateBatch(custTaskDealSQL2, "dataSource");
                                    log.debug("【SQL返回结果】：" + batchSQLResult2.toString());
                                    senderGuidList.add(fdd_customerid);
                                    senderNameList.add(hjx_customeridlist.get(f).get("sender_name"));
                                }
                            }
                            //往 fdd_contract_list 表中记录合同数据
                            log.debug("【signerGuidList接收方guid】：" + signerGuidList + "、【signerNameList接收方名称】：" + signerNameList.join('/'));
                            log.debug("【senderGuidList发起方guid】：" + senderGuidList + "、【senderNameList发起方名称】：" + senderNameList.join('/'));

                            def departmentoid, leaseapplicationtimestart, leaseapplicationtimesend, currentapplicationperiod, selectsql = '';
                            List selectList = new ArrayList<>();
                            if (tabname == 'tabcwo_business_info') {//租赁工单一年上下、广告租赁工单
                                selectsql = "select zl_departmentoid, zl_leaseapplicationtimestart, zl_leaseapplicationtimesend, zl_currentapplicationperiod from tabcwo_business_info t left join objective o on o.objective_guid = t.relation_id where o.workorderid = '" + workorderid + "'";
                            } else if (tabname == 'tabcwo_contract_change') {//合同变更工单
                                selectsql = "select departmentoid as zl_departmentoid, zl_leaseapplicationtimestart, zl_leaseapplicationtimesend, zl_currentapplicationperiod from tabcwo_contract_change t left join objective o on o.objective_guid = t.relation_id where o.workorderid = '" + workorderid + "'";
                            } else if (tabname == 'tabcback_rent') { //退租工单
                                selectsql = "select departmentoid as zl_departmentoid, leaseapplicationtimestart as zl_leaseapplicationtimestart, leaseapplicationtimesend as zl_leaseapplicationtimesend, currentapplicationperiod as zl_currentapplicationperiod from tabcback_rent t left join objective o on o.objective_guid = t.relation_id where o.workorderid = '" + workorderid + "'";
                            }
                            selectList = eliteBean.chaxun_sql(selectsql, "dataSource");
                            departmentoid = selectList[0].get("zl_departmentoid");
                            leaseapplicationtimestart = selectList[0].get("zl_leaseapplicationtimestart");
                            leaseapplicationtimesend = selectList[0].get("zl_leaseapplicationtimesend");
                            currentapplicationperiod = selectList[0].get("zl_currentapplicationperiod");

                            int insertsum = eliteBean.update("insert into fdd_contract_list( contractlist_guid, contractid, contracttype, contractfileid, workorderid, businessnumber, departmentoid, signer_guid, signer_name, sender_guid, sender_name, leaseapplicationtimestart, leaseapplicationtimesend, currentapplicationperiod, createddate) " +
                                    "values( UUID(), '" + contractid2 + "', '1', '" + ModelID + "', '" + workorderid + "', '" + businessnumber + "', '" + departmentoid + "', '" + signerGuidList + "', '" + signerNameList.join('/') + "', '" + senderGuidList + "', '" + senderNameList.join('/') + "', '" + leaseapplicationtimestart + "', '" + leaseapplicationtimesend + "', '" + currentapplicationperiod + "', NOW())", "dataSource");
                            log.debug("往 fdd_contract_lise 表中记录合同数据返回结果：" + insertsum);
                        }
                    } else {
                        result.put("code", 1009);
                        result.put("msg", "拼接的模板参数为空,请联系管理员");

                        JSONObject curJson = new JSONObject();
                        curJson.put("deslcode", -2);
                        curJson.put("dealinfo", "拼接的模板参数为空,请联系管理员");
                        conArr.add(curJson);

                    }
                }
            }

        } catch (Exception e) {
            result.put("code", 1008);
            result.put("msg", e.getMessage());
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "内部合同模板拼接-P1", "apiFDDMoudle", callJson, result.toString(), (System.currentTimeMillis() - startTime).toString(), "/");
        }

        result.put("dealresult", conArr);
        return result;

    }
}